<?php defined('SYSPATH') or die('No direct script access.');

class Model_Review
{ 
    const REVIEWS_PER_PAGE = 10;
    public static $available_sort = array('usefulness', 'date'); 
    
    public static function get_reviews($entity, $page = null, $get_count = false, $order_by = 'usefulness')
    {        
        // Если ищем по товару, а он не соотнесен к модели
        if ($entity instanceof Model_Product) {
            $model_id = $entity->model_id;
            if (!$entity->model_id) {
                // Продукт не соотнесен к модели, вернем пустой массив
                if ($get_count) {
                    return 0;    
                }
                return array();
            }   
        } else if ($entity instanceof Model_Model) {
            $model_id = $entity->id;
        } else {
            throw new Model_Exception('Некорректный тип');
        }
        
        if (!$order_by) {
            $order_by = 'usefulness';
        }
        if (!in_array($order_by, self::$available_sort) ) {
            throw new Model_Exception('Некорректное поле для сортировки');    
        }
        
        if ($reviews = Cache::instance()->get('reviews_'.$model_id.'_'.$page.'_'.$get_count.'_'.$order_by)) {
            return $reviews;
        }        
             
        /*$query = DB::select()->from(
                    array(ORM::factory('review_yandexmarket')->get_reviews_query($entity)
                    ->union(ORM::factory('review_rozetka')->get_reviews_query($entity)), 'table')
                ); */
        $query = ORM::factory('review_yandexmarket')->get_reviews_query($entity); 
            
        if ($page) {
            $count = self::get_reviews_per_page();
            $offset = ($page - 1) * $count;
            $query->offset($offset)->limit($count);    
        }
        
        if ($order_by) {
            $query->order_by($order_by, 'DESC');   
        }
        
        $query = ORM::factory('review_irecommend')->get_reviews_query($entity)
            ->union($query);
        
        if ($get_count) {
            /*$count = $query->select(array(DB::expr('COUNT(*)'), 'count'))->execute()->as_array();
            $count = $count[0]['count'];
            Cache::instance()->set('reviews_'.$model_id.'_'.$page.'_'.$get_count.'_'.$order_by, $count); 
            return $count;   */
        }
        $reviews = $query->execute()->as_array();
        Cache::instance()->set('reviews_'.$model_id.'_'.$page.'_'.$get_count.'_'.$order_by, Model_Main::get_array($reviews)); 
        return $reviews;       
    }
    
    public static function get_reviews_per_page()
    {
        return self::REVIEWS_PER_PAGE;
    }
    
    public static function clear_cache(Model_Model $model)
    {
        // TODO сделать теггирование
        Cache::instance()->delete_all();
    }
}
